using System.Diagnostics;
using System.Text;
using MultiAgentsShared;
using Debug = MultiAgentsShared.Debug;

namespace MultiAgentsClient.Tools;

[GptToolSet("Python ToolSet", "")]
public class PythonToolProvider
{
    [GptFunc("Execute python code and get its outputs", true)]
    public static CmdResult ExecutePythonCode(
        [GptFuncParam("python codes to execute")] string scriptContent
        )
    {
        string pathVariable = Environment.GetEnvironmentVariable("PATH") ?? throw Debug.ShouldNotHappen();
        Debug.Log("PATH Environment Variable: " + pathVariable);

        // Save the script content to a temporary Python file
        string tempScriptPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".py");
        File.WriteAllText(tempScriptPath, scriptContent);

        string pythonInterpreter = "python"; // Assumes Python is in PATH, use full path otherwise

        // Set up the process start info
        ProcessStartInfo startInfo = new()
        {
            FileName = pythonInterpreter,
            Arguments = tempScriptPath,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true,
            StandardOutputEncoding = Encoding.UTF8,
            StandardErrorEncoding = Encoding.UTF8
        };

        // Execute the process
        using Process process = new();
        process.StartInfo = startInfo;

        try
        {
            process.Start();

            // Capture output and error
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();

            process.WaitForExit();

            // Clean up the temp script file
            File.Delete(tempScriptPath);

            // Return the result
            return new CmdResult
            {
                Output = output,
                Error = error,
                ExitCode = process.ExitCode
            };
        }
        catch (Exception ex)
        {
            return new CmdResult
            {
                Output = string.Empty,
                Error = ex.Message,
                ExitCode = -1
            };
        }
    }
}
